package org.jeecg.modules.demo.postorder.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.postorder.entity.CaSign;
import org.jeecg.modules.demo.postorder.entity.Postorder;
import org.jeecg.modules.demo.postorder.service.IPostorderService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: postorder
 * @Author: jeecg-boot
 * @Date:   2025-04-27
 * @Version: V1.0
 */
@Api(tags="postorder")
@RestController
@RequestMapping("/postorder/postorder")
@Slf4j
public class PostorderController extends JeecgController<Postorder, IPostorderService> {
	@Autowired
	private IPostorderService postorderService;

	/**
	 * 分页列表查询
	 *
	 * @param postorder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "postorder-分页列表查询")
	@ApiOperation(value="postorder-分页列表查询", notes="postorder-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<Postorder>> queryPageList(Postorder postorder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Postorder> queryWrapper = QueryGenerator.initQueryWrapper(postorder, req.getParameterMap());
		Page<Postorder> page = new Page<Postorder>(pageNo, pageSize);
		IPage<Postorder> pageList = postorderService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param postorder
	 * @return
	 */
	@AutoLog(value = "postorder-添加")
	@ApiOperation(value="postorder-添加", notes="postorder-添加")
	//@RequiresPermissions("postorder:postorder:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody Postorder postorder) {
		postorderService.save(postorder);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param postorder
	 * @return
	 */
	@AutoLog(value = "postorder-编辑")
	@ApiOperation(value="postorder-编辑", notes="postorder-编辑")
	//@RequiresPermissions("postorder:postorder:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody Postorder postorder) {
		postorderService.updateById(postorder);
		return Result.OK("操作成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "postorder-通过id删除")
	@ApiOperation(value="postorder-通过id删除", notes="postorder-通过id删除")
	//@RequiresPermissions("postorder:postorder:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		postorderService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "postorder-批量删除")
	@ApiOperation(value="postorder-批量删除", notes="postorder-批量删除")
	//@RequiresPermissions("postorder:postorder:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.postorderService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "postorder-通过id查询")
	@ApiOperation(value="postorder-通过id查询", notes="postorder-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<Postorder> queryById(@RequestParam(name="id",required=true) String id) {
		Postorder postorder = postorderService.getById(id);
		if(postorder==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(postorder);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param postorder
    */
    //@RequiresPermissions("postorder:postorder:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Postorder postorder) {
        return super.exportXls(request, postorder, Postorder.class, "postorder");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("postorder:postorder:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Postorder.class);
    }


	 /**
	  * 获取签章
	  */
	 @GetMapping("/getfindcode")
	 public String getFindcode(@RequestParam(value="qymc")String name) {
		 String body = getbody(name);
		 if(body.equals("1")){
			 body =  getbodygz(name);
		 }
		 return body;
	 }

	 public String getbody(String name){

		 String url = getStrUrl("caurl")+"/v2/api/seal/getSealBase64ByUserId";
		 RestTemplate restTemplate = new RestTemplate();
		 // 准备请求头
		 HttpHeaders headers = new HttpHeaders();
		 headers.setContentType(MediaType.APPLICATION_JSON);
		 // 原始JSON字符串
		 String jsonBody = "{callValue:\'"+name+"合同章\',callType:3}";
		 // 创建请求实体
		 HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);

		 // 发送POST请求
		 ResponseEntity<String> response = restTemplate.exchange(
				 url,
				 HttpMethod.POST,
				 requestEntity,
				 String.class
		 );

		 String body = response.getBody();
		 JSONObject jsonObject = JSON.parseObject(body);
		 if (jsonObject.get("code").toString().equals("200")) {
			 JSONArray jsonArray = (JSONArray) jsonObject.get("data");
			 if (jsonArray != null && jsonArray.size() > 0) {
				 body = jsonArray.getString(0);
			 }
		 } else {
			 body = "1";
		 }
		 return body;


//		 String params = "{callValue:\'"+name+"合同章\',callType:3}";
//		 HttpRequest request = HttpRequest.post(url).body(params);
//		 request.removeHeader(Header.USER_AGENT);
//
//		 String body = request.execute().body();
//		 System.out.println(body);
//		 JSONObject jsonObject = JSON.parseObject(body);
//		 if (jsonObject.get("code").toString().equals("200")) {
//			 JSONArray jsonArray = (JSONArray) jsonObject.get("data");
//			 if (jsonArray != null && jsonArray.size() > 0)
//				 body = jsonArray.getString(0);
//		 } else {
//			 body = "1";
//		 }
//		 return body;

	 }

	 public String getbodygz(String name){

		 String url = getStrUrl("caurl")+"/v2/api/seal/getSealBase64ByUserId";
		 RestTemplate restTemplate = new RestTemplate();
		 // 准备请求头
		 HttpHeaders headers = new HttpHeaders();
		 headers.setContentType(MediaType.APPLICATION_JSON);
		 // 原始JSON字符串
		 String jsonBody = "{callValue:\'"+name+"公章\',callType:3}";
		 // 创建请求实体
		 HttpEntity<String> requestEntity = new HttpEntity<>(jsonBody, headers);

		 // 发送POST请求
		 ResponseEntity<String> response = restTemplate.exchange(
				 url,
				 HttpMethod.POST,
				 requestEntity,
				 String.class
		 );

		 String body = response.getBody();
		 JSONObject jsonObject = JSON.parseObject(body);
		 if (jsonObject.get("code").toString().equals("200")) {
			 JSONArray jsonArray = (JSONArray) jsonObject.get("data");
			 if (jsonArray != null && jsonArray.size() > 0) {
				 body = jsonArray.getString(0);
			 }
		 } else {
			 body = "1";
		 }
		 return body;

//		 String url = getStrUrl("caurl")+"/v2/api/seal/getSealBase64ByUserId";
//		 String params = "{callValue:\'"+name+"公章\',callType:3}";
//		 HttpRequest request = HttpRequest.post(url).body(params);
//		 RestTemplate restTemplate = new RestTemplate();
//		 request.removeHeader(Header.USER_AGENT);
//		 String body = request.execute().body();
//		 System.out.println(body);
//		 JSONObject jsonObject = JSON.parseObject(body);
//		 if (jsonObject.get("code").toString().equals("200")) {
//			 JSONArray jsonArray = (JSONArray) jsonObject.get("data");
//			 if (jsonArray != null && jsonArray.size() > 0)
//				 body = jsonArray.getString(0);
//		 } else {
//			 body = "1";
//		 }
//		 return body;
	 }


	 public String getStrUrl(String strtrl) {
		 String url = postorderService.getURL(strtrl);
		 return url;
	 }

	 @GetMapping("/tyrcasign")
	 public Result<?> tyrcasign(@RequestParam(name="hetid") String hetid){
		 try{
			 CaSign ca  =new CaSign();
			 ca.setObjid(hetid);
			 ca.setObjtag("TL_HET");
			 ca.setSigntag("CMRJS");
			 CaSign model = postorderService.casignById(ca);
			 if(model !=null){
				 return Result.ok( "已盖章");
			 }else{
				 return Result.error(-100,"未找到签章信息!");
			 }

		 }catch(Exception e){
			 e.printStackTrace();
		 }

		 return null;
	 }

	 @GetMapping("/cyrcasign")
	 public Result<?> cyrcasign(@RequestParam(name="hetid") String hetid){
		 try{
			 CaSign ca  =new CaSign();
			 ca.setObjid(hetid);
			 ca.setObjtag("TL_HET");
			 ca.setSigntag("MSR");
			 CaSign model =postorderService.casignById(ca);
			 if(model !=null){
				 return Result.ok("已盖章");
			 }else{
				 return Result.error(-100,"未找到签章信息!");
			 }
		 }catch(Exception e){
			 e.printStackTrace();
		 }

		 return null;
	 }

}
